package com.app.game.other;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;

import com.app.factories.BetFactory;
import com.app.factories.impl.DozenBetFactory;
import com.app.factories.impl.InsideBetFactory;
import com.app.factories.impl.OutsideBetFactory;
import com.app.game.bet.Bet;
import com.app.game.control.HumanPlayer;

public class AiPlayerFasade {
	private ArrayList<Player> players= new ArrayList<Player>();
	private static BetFactory[] factories= {new OutsideBetFactory(),  new DozenBetFactory(),new InsideBetFactory()}; 
	private HashMap<Player, List<Bet>> betList = new HashMap<>();
	private ArrayList<PlayerFix> updates = new ArrayList<>();
	public AiPlayerFasade(){
		 
		for(int i = 0 ; i < 6 ; ++i){
			HumanPlayer p = new HumanPlayer("Komputer " + (i+2));
			p.setId(i+2);
			Credit c = new Credit();
			c.setValue(1000);
			p.setCredits(c);
			players.add(p);
		}
	}
	
	public void pretendBets(){
		betList.clear();
		for(Player p : players){
			Random r = new Random();
			int bets = r.nextInt(3);
			List<Bet> b = new ArrayList<Bet>();
			for(int i = 0 ; i < bets ; ++i){
				Credit c = new Credit();
				int value ;
				value = r.nextInt(100);
				value*=5;
				c.setValue(validateValue(value, p.getCredits().getValue()));
				int index = r.nextInt(2);
				b.add(p.makeBet(factories[index], r.nextInt(6), c));
			}
			betList.put(p, b);
		}
	}
	
	public void checkRes(int res){
		Set<Entry<Player, List<Bet>>> s = betList.entrySet();
		Iterator<Entry<Player, List<Bet>>> i = s.iterator();
		updates.clear();
		while(i.hasNext()){
			Entry<Player, List<Bet>> entry = i.next();
			Player p = entry.getKey();
			List<Bet> b = entry.getValue();
			for(Bet bet: b){
				p.getCredits().add(bet.checkResults(res));
			}
			if(p.getCredits().getValue() > 0){
				PlayerFix pf = new PlayerFix(p.getId(), p.getCredits().getValue(), p.getName());
				updates.add(pf);
			}
			if(p.getCredits().getValue() <= 0){
				PlayerFix pf = new PlayerFix(p.getId(), 0, p.getName());
				players.remove(p);
				updates.add(pf);
			}
		}
	}
	private int validateValue(int value, int max){
		if(value > max){
			value-=5;
			return validateValue(value, max);
		}else{
			return value;
		}
	}
	public HashMap<Integer, Player> getPlayers(){
		HashMap<Integer,Player> map = new HashMap<>();
		for(Player p :players){
			map.put(p.getId(), p);	
		}
		return map;
	}
	
	public List<PlayerFix> getUpdates(){
		if(updates.isEmpty()){
			for(Player p :players){
				updates.add(new PlayerFix(p.getId(),p.getCredits().getValue(),p.getName()));
			}
		}
		return updates;
	}
	public int getActiveComputersCount(){
		int c = 0;
		for(PlayerFix pf : updates){
			if(pf.getValue() >0){
				c++;
			}
		}
		return c;
	}
}
